package com.sj.purchase.modules.helper.config.task;

import com.sj.purchase.modules.helper.model.OutBoundUniqueCode;
import com.sj.purchase.modules.helper.repository.OutBoundUniqueCodeRepository;
import com.sj.purchase.util.Date2StrUtils;
import com.sj.purchase.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;

/**
 * @author yangrd
 * @date 2018/8/16
 **/
@Component
public class OutBoundUniqueCodeTask {

    private RestTemplate restTemplate;

    private String api;

    private OutBoundUniqueCodeRepository repository;

    @Autowired
    public OutBoundUniqueCodeTask(RestTemplate restTemplate, OutBoundUniqueCodeRepository repository, @Value("${sj.ecwms}") String wmsApi) {
        this.restTemplate = restTemplate;
        this.repository = repository;
        this.api = wmsApi + "/outbound-serial-no/?start={1}&end={2}";
    }

    /**
     * 同步wms数据
     * @param day yyyy/MM/dd
     */
    public void syncWMSData(String day) {
        Date tomorrow = DateUtils.addDays(Date2StrUtils.parse(day), 1);
        String tomorrowStr = Date2StrUtils.str(tomorrow);
        List<OutBoundUniqueCode> list = restTemplate.exchange(api, HttpMethod.GET, null, new ParameterizedTypeReference<List<OutBoundUniqueCode>>() {
        },day,tomorrowStr).getBody();
        repository.save(list);
    }

    /**
     * 清理两个月之前的数据 70天前的
     */
    public void cleaned2MonthsAgoData(){
        Date ago = DateUtils.addDays(new Date(), 70);
        repository.deleteAllByCreateDateBefore(ago);
    }

}
